<script lang="ts" setup>
import type { DressResourceApi } from '#/api/wedding/dressresource';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, QRCode, message, Space, Divider } from 'ant-design-vue';

import { generateShareCode } from '#/utils/share-code';

defineOptions({ name: 'QRPreviewModal' });

const dressData = ref<DressResourceApi.DressResource>();
const qrCodeUrl = ref('');
const isGalleryMode = ref(false);

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      dressData.value = undefined;
      qrCodeUrl.value = '';
      isGalleryMode.value = false;
      return;
    }
    
    // 获取数据
    const data = modalApi.getData<any>();
    if (data) {
      // 判断是否是婚纱展示主页模式
      if (data.isGallery) {
        isGalleryMode.value = true;
        qrCodeUrl.value = generateGalleryUrl();
      } else {
        isGalleryMode.value = false;
        dressData.value = data;
        // 生成预览链接
        qrCodeUrl.value = generatePreviewUrl(data);
      }
    }
  },
});

// 生成预览链接
function generatePreviewUrl(data: DressResourceApi.DressResource) {
  const baseUrl = window.location.origin;
  // 生成加密的分享码
  const shareCode = generateShareCode(data.id);
  const previewPath = `/wedding/dress-preview/${shareCode}`;
  return `${baseUrl}${previewPath}`;
}

// 生成婚纱展示主页链接
function generateGalleryUrl() {
  const baseUrl = window.location.origin;
  return `${baseUrl}/wedding/dress-gallery`;
}

// 使用工具函数生成分享码

// 复制链接
function copyLink() {
  if (qrCodeUrl.value) {
    navigator.clipboard.writeText(qrCodeUrl.value).then(() => {
      message.success('链接已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败，请手动复制');
    });
  }
}

// 在新窗口打开预览链接
function openPreviewLink() {
  if (qrCodeUrl.value) {
    window.open(qrCodeUrl.value, '_blank');
  }
}

// 下载二维码
function downloadQRCode() {
  const canvas = document.querySelector('.qr-code canvas') as HTMLCanvasElement;
  if (canvas) {
    const link = document.createElement('a');
    link.download = `婚纱-${dressData.value?.dressName || dressData.value?.id}-二维码.png`;
    link.href = canvas.toDataURL();
    link.click();
  }
}

// 分享到微信
function shareToWeChat() {
  if (qrCodeUrl.value) {
    const shareText = `查看婚纱详情：${dressData.value?.dressName || '婚纱'}\n${qrCodeUrl.value}`;
    navigator.clipboard.writeText(shareText).then(() => {
      message.success('分享内容已复制，可粘贴到微信发送');
    }).catch(() => {
      message.error('复制失败');
    });
  }
}

const title = computed(() => {
  if (isGalleryMode.value) {
    return '婚纱展示主页 - 扫码浏览';
  }
  return `扫码预览 - ${dressData.value?.dressName || '婚纱详情'}`;
});
</script>

<template>
  <Modal :title="title" width="600px">
    <div v-if="isGalleryMode || dressData" class="space-y-6">
      <!-- 婚纱展示主页说明 -->
      <div v-if="isGalleryMode" class="bg-gradient-to-r from-pink-50 to-purple-50 p-4 rounded-lg">
        <h3 class="text-lg font-semibold mb-3 flex items-center gap-2">
          <IconifyIcon icon="lucide:layout-grid" />
          婚纱展示主页
        </h3>
        <div class="space-y-2 text-sm text-gray-700">
          <p>• 展示所有可租赁的婚纱款式</p>
          <p>• 支持搜索和筛选功能（品牌、颜色等）</p>
          <p>• 点击任意婚纱查看详细信息</p>
          <p>• 适合客户浏览和挑选婚纱</p>
        </div>
      </div>

      <!-- 婚纱基本信息 -->
      <div v-if="!isGalleryMode" class="bg-gray-50 p-4 rounded-lg">
        <h3 class="text-lg font-semibold mb-3 flex items-center gap-2">
          <IconifyIcon icon="lucide:dress" />
          婚纱信息
        </h3>
        <div class="grid grid-cols-2 gap-3 text-sm">
          <div>
            <span class="text-gray-600">婚纱名称：</span>
            <span class="font-medium">{{ dressData.dressName || '未设置' }}</span>
          </div>
          <div>
            <span class="text-gray-600">婚纱编码：</span>
            <span class="font-medium">{{ dressData.dressCode || '未设置' }}</span>
          </div>
          <div>
            <span class="text-gray-600">品牌：</span>
            <span class="font-medium">{{ dressData.brand || '未设置' }}</span>
          </div>
          <div>
            <span class="text-gray-600">颜色：</span>
            <span class="font-medium">{{ dressData.color || '未设置' }}</span>
          </div>
          <div>
            <span class="text-gray-600">尺码：</span>
            <span class="font-medium">{{ dressData.size || '未设置' }}</span>
          </div>
          <div>
            <span class="text-gray-600">租赁价格：</span>
            <span class="font-medium text-red-600">¥{{ dressData.rentalPrice || 0 }}/天</span>
          </div>
          <div>
            <span class="text-gray-600">库存数量：</span>
            <span class="font-medium">{{ dressData.inventoryCount || 0 }}件</span>
          </div>
          <div>
            <span class="text-gray-600">状态：</span>
            <span 
              class="font-medium px-2 py-1 rounded text-xs"
              :class="{
                'bg-green-100 text-green-800': dressData.status === 'available',
                'bg-blue-100 text-blue-800': dressData.status === 'rented',
                'bg-yellow-100 text-yellow-800': dressData.status === 'maintenance',
                'bg-gray-100 text-gray-800': dressData.status === 'disabled',
              }"
            >
              {{ 
                dressData.status === 'available' ? '可用' :
                dressData.status === 'rented' ? '租赁中' :
                dressData.status === 'maintenance' ? '维护中' :
                dressData.status === 'disabled' ? '停用' : '未知'
              }}
            </span>
          </div>
        </div>
      </div>

      <!-- 二维码区域 -->
      <div class="text-center">
        <h3 class="text-lg font-semibold mb-3 flex items-center justify-center gap-2">
          <IconifyIcon icon="lucide:qr-code" />
          扫码预览
        </h3>
        <div class="qr-code flex justify-center mb-4">
          <QRCode 
            :value="qrCodeUrl" 
            :size="200"
            :bordered="false"
            color="#1890ff"
          />
        </div>
        <p class="text-sm text-gray-600 mb-4">
          {{ isGalleryMode ? '使用手机扫描二维码，即可浏览所有婚纱款式' : '使用手机扫描二维码，即可在移动端查看婚纱详情' }}
        </p>
        
        <!-- 预览链接 -->
        <div class="bg-blue-50 p-3 rounded-lg mb-4">
          <p class="text-sm text-gray-600 mb-2">预览链接：</p>
          <div class="flex items-center gap-2">
            <input 
              :value="qrCodeUrl" 
              readonly 
              class="flex-1 px-3 py-2 border rounded text-sm bg-white"
            />
            <Button size="small" type="primary" @click="openPreviewLink" title="在新窗口打开">
              <IconifyIcon icon="lucide:external-link" />
            </Button>
            <Button size="small" @click="copyLink" title="复制链接">
              <IconifyIcon icon="lucide:copy" />
            </Button>
          </div>
        </div>
      </div>

      <Divider />

      <!-- 操作按钮 -->
      <div class="flex justify-center gap-3">
        <Button type="primary" @click="downloadQRCode">
          <template #icon>
            <IconifyIcon icon="lucide:download" />
          </template>
          下载二维码
        </Button>
        <Button @click="copyLink">
          <template #icon>
            <IconifyIcon icon="lucide:copy" />
          </template>
          复制链接
        </Button>
        <Button @click="shareToWeChat">
          <template #icon>
            <IconifyIcon icon="lucide:share" />
          </template>
          分享到微信
        </Button>
      </div>

      <!-- 使用说明 -->
      <div class="bg-yellow-50 p-4 rounded-lg">
        <h4 class="font-medium text-yellow-800 mb-2 flex items-center gap-2">
          <IconifyIcon icon="lucide:info" />
          使用说明
        </h4>
        <ul v-if="isGalleryMode" class="text-sm text-yellow-700 space-y-1">
          <li>• 客户扫描二维码后可浏览所有可租赁婚纱</li>
          <li>• 支持搜索和筛选功能，快速找到心仪婚纱</li>
          <li>• 点击任意婚纱查看详细信息和图片</li>
          <li>• 可打印二维码用于店内展示或宣传</li>
          <li>• 适合客户自助浏览和挑选婚纱</li>
        </ul>
        <ul v-else class="text-sm text-yellow-700 space-y-1">
          <li>• 客户扫描二维码后可在手机端查看婚纱详情</li>
          <li>• 包含婚纱图片、基本信息、价格等详细内容</li>
          <li>• 支持分享给客户，方便客户了解婚纱详情</li>
          <li>• 二维码可下载打印，用于线下展示</li>
          <li>• 客户可从详情页返回婚纱展示主页浏览更多款式</li>
        </ul>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.qr-code {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
